/**
 * 物理库相关操作
 * by wyy
 */
class physicsUtil extends eui.Component implements eui.UIComponent {
    private static instance: physicsUtil;
    public phyWorld: p2.World;
    public phyFactor: number = 50;
    public debugDraw: p2DebugDraw;
    public debugSprite: egret.Sprite;

    constructor() {
        super();
        this.init();
    }
    static getInstance(): physicsUtil {
        (!this.instance) && (this.instance = new physicsUtil());
        return this.instance;
    }
    private init() {
    }

    //创建物理世界
    public createPhyWorld(gravity: number) {
        this.phyWorld = new p2.World({
            gravity: [0, gravity]
        });
        let world = this.phyWorld;
        world.sleepMode = p2.World.BODY_SLEEPING;

        world.applyGravity = true;
        world.applyDamping = true;

        /*this.debugDraw = new p2DebugDraw(this.phyWorld)
        this.debugSprite = new egret.Sprite();
        this.debugDraw.setSprite(this.debugSprite);
        Frame.Display.stage.addChild(this.debugSprite);*/

        //物体坐标同步
        this.addEventListener(egret.Event.ENTER_FRAME, () => {
            world.step(1 / 60);
            let l = world.bodies.length;
            for (let i: number = 0; i < l; i++) {
                this.syncDisplay(world.bodies[i]);
            }
            //this.debugDraw.drawDebug();
        }, this);

        return this.phyWorld;
    }

    //将显示与物理同步
    private syncDisplay(body: p2.Body) {
        let shape = body.displays[0];
        let stageHeight = egret.MainContext.instance.stage.stageHeight;
        let p = shape.parent ? shape.parent.globalToLocal(body.position[0] * this.phyFactor, stageHeight - (body.position[1] * this.phyFactor)) : null;
        if ((shape) && (p)) {
            shape.x = p.x;
            shape.y = p.y;
            shape.rotation = 360 - (body.angle + body.shapes[0].angle) * 180 / Math.PI;
        }
    }
    //p2和egret坐标变换
    public posP2ToEgret(x: number, y: number): number[] {
        let stageH = egret.MainContext.instance.stage.stageHeight;
        let rX = Math.floor(x) * this.phyFactor;
        let rY = Math.floor(stageH - y) * this.phyFactor;
        return [rX, rY];
    }
    public posEgretToP2(x: number, y: number): number[] {
        let stageH = egret.MainContext.instance.stage.stageHeight;
        let rX = Math.floor(x) / this.phyFactor;
        let rY = Math.floor(stageH - y) / this.phyFactor;
        return [rX, rY];
    }
    //长度egret to p2
    lengthEgretToP2(l: number) {
        return l / this.phyFactor;
    }
}